/**
 * 实时监控仪表板主组件
 * 
 * 功能特性：
 * - 实时系统状态监控
 * - 性能指标展示
 * - 告警信息管理
 * - 资源使用情况
 * - 自定义仪表板布局
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

import React, { useState, useEffect, useCallback } from 'react';
import { 
  Card, 
  Row, 
  Col, 
  Statistic, 
  Progress, 
  Timeline, 
  Badge, 
  Alert, 
  Button, 
  Select, 
  DatePicker, 
  Space, 
  Divider,
  Tooltip,
  Modal,
  Form,
  Input,
  Switch,
  InputNumber,
  message,
  Spin
} from 'antd';
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer
} from 'recharts';
import {
  DashboardOutlined,
  AlertOutlined,
  LineChartOutlined,
  BarChartOutlined,
  PieChartOutlined,
  SettingOutlined,
  ReloadOutlined,
  FullscreenOutlined,
  DownloadOutlined,
  BellOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface SystemMetrics {
  timestamp: string;
  cpuUsage: number;
  memoryUsage: number;
  diskUsage: number;
  networkIn: number;
  networkOut: number;
  activeConnections: number;
  responseTime: number;
  throughput: number;
}

interface AlertInfo {
  id: string;
  type: 'error' | 'warning' | 'info';
  title: string;
  message: string;
  timestamp: string;
  status: 'active' | 'resolved';
  severity: 'low' | 'medium' | 'high' | 'critical';
}

interface DashboardConfig {
  refreshInterval: number;
  enabledWidgets: string[];
  alertThresholds: {
    cpu: number;
    memory: number;
    disk: number;
    responseTime: number;
  };
  theme: 'light' | 'dark';
}

const RealTimeDashboard: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [metrics, setMetrics] = useState<SystemMetrics[]>([]);
  const [alerts, setAlerts] = useState<AlertInfo[]>([]);
  const [config, setConfig] = useState<DashboardConfig>({
    refreshInterval: 5000,
    enabledWidgets: ['system', 'performance', 'alerts'],
    alertThresholds: {
      cpu: 80,
      memory: 85,
      disk: 90,
      responseTime: 5000
    },
    theme: 'light'
  });
  const [selectedTimeRange, setSelectedTimeRange] = useState('1h');
  const [configModalVisible, setConfigModalVisible] = useState(false);

  // 生成模拟实时数据
  const generateMockMetrics = useCallback((): SystemMetrics => {
    const now = new Date();
    return {
      timestamp: now.toISOString(),
      cpuUsage: Math.random() * 100,
      memoryUsage: Math.random() * 100,
      diskUsage: Math.random() * 100,
      networkIn: Math.random() * 1000,
      networkOut: Math.random() * 1000,
      activeConnections: Math.floor(Math.random() * 1000) + 100,
      responseTime: Math.random() * 2000 + 100,
      throughput: Math.random() * 500 + 50
    };
  }, []);

  // 检查告警条件
  const checkAlerts = useCallback((metrics: SystemMetrics): AlertInfo[] => {
    const newAlerts: AlertInfo[] = [];
    const { alertThresholds } = config;

    if (metrics.cpuUsage > alertThresholds.cpu) {
      newAlerts.push({
        id: `cpu-${Date.now()}`,
        type: 'warning',
        title: 'CPU使用率过高',
        message: `CPU使用率达到 ${metrics.cpuUsage.toFixed(1)}%`,
        timestamp: metrics.timestamp,
        status: 'active',
        severity: metrics.cpuUsage > 95 ? 'critical' : 'high'
      });
    }

    if (metrics.memoryUsage > alertThresholds.memory) {
      newAlerts.push({
        id: `memory-${Date.now()}`,
        type: 'warning',
        title: '内存使用率过高',
        message: `内存使用率达到 ${metrics.memoryUsage.toFixed(1)}%`,
        timestamp: metrics.timestamp,
        status: 'active',
        severity: metrics.memoryUsage > 95 ? 'critical' : 'high'
      });
    }

    if (metrics.diskUsage > alertThresholds.disk) {
      newAlerts.push({
        id: `disk-${Date.now()}`,
        type: 'error',
        title: '磁盘空间不足',
        message: `磁盘使用率达到 ${metrics.diskUsage.toFixed(1)}%`,
        timestamp: metrics.timestamp,
        status: 'active',
        severity: metrics.diskUsage > 98 ? 'critical' : 'high'
      });
    }

    if (metrics.responseTime > alertThresholds.responseTime) {
      newAlerts.push({
        id: `response-${Date.now()}`,
        type: 'warning',
        title: '响应时间过长',
        message: `平均响应时间达到 ${metrics.responseTime.toFixed(0)}ms`,
        timestamp: metrics.timestamp,
        status: 'active',
        severity: metrics.responseTime > 10000 ? 'critical' : 'medium'
      });
    }

    return newAlerts;
  }, [config]);

  // 获取实时数据
  const fetchRealTimeData = useCallback(async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const newMetrics = generateMockMetrics();
      const newAlerts = checkAlerts(newMetrics);
      
      setMetrics(prev => {
        const updated = [...prev, newMetrics];
        // 保持最近100个数据点
        return updated.slice(-100);
      });
      
      setAlerts(prev => {
        const updated = [...newAlerts, ...prev];
        // 保持最近50个告警
        return updated.slice(-50);
      });
    } catch (error) {
      message.error('获取监控数据失败');
    } finally {
      setLoading(false);
    }
  }, [generateMockMetrics, checkAlerts]);

  // 初始化数据和定时器
  useEffect(() => {
    fetchRealTimeData();
    const interval = setInterval(fetchRealTimeData, config.refreshInterval);
    return () => clearInterval(interval);
  }, [fetchRealTimeData, config.refreshInterval]);

  // 处理告警确认
  const handleAlertAcknowledge = (alertId: string) => {
    setAlerts(prev => prev.map(alert => 
      alert.id === alertId 
        ? { ...alert, status: 'resolved' as const }
        : alert
    ));
    message.success('告警已确认');
  };

  // 处理配置更新
  const handleConfigUpdate = (values: Partial<DashboardConfig>) => {
    setConfig(prev => ({ ...prev, ...values }));
    setConfigModalVisible(false);
    message.success('配置已更新');
  };

  // 导出数据
  const handleExportData = () => {
    const dataStr = JSON.stringify({
      metrics,
      alerts,
      config,
      exportTime: new Date().toISOString()
    }, null, 2);
    
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `monitoring-data-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    message.success('数据导出成功');
  };

  // 获取告警统计
  const getAlertStats = () => {
    const active = alerts.filter(a => a.status === 'active');
    const critical = active.filter(a => a.severity === 'critical').length;
    const high = active.filter(a => a.severity === 'high').length;
    const medium = active.filter(a => a.severity === 'medium').length;
    const low = active.filter(a => a.severity === 'low').length;
    
    return { total: active.length, critical, high, medium, low };
  };

  const alertStats = getAlertStats();
  const latestMetrics = metrics[metrics.length - 1];

  return (
    <div className="real-time-dashboard">
      {/* 顶部工具栏 */}
      <div className="dashboard-toolbar">
        <Space>
          <h2>
            <DashboardOutlined /> 实时监控仪表板
          </h2>
          <Badge count={alertStats.total} showZero>
            <BellOutlined />
          </Badge>
        </Space>
        
        <Space>
          <Select 
            value={selectedTimeRange} 
            onChange={setSelectedTimeRange}
            style={{ width: 120 }}
          >
            <Option value="5m">5分钟</Option>
            <Option value="15m">15分钟</Option>
            <Option value="1h">1小时</Option>
            <Option value="6h">6小时</Option>
            <Option value="24h">24小时</Option>
          </Select>
          
          <Button 
            icon={<ReloadOutlined />} 
            onClick={fetchRealTimeData}
            loading={loading}
          >
            刷新
          </Button>
          
          <Button 
            icon={<SettingOutlined />} 
            onClick={() => setConfigModalVisible(true)}
          >
            设置
          </Button>
          
          <Button 
            icon={<DownloadOutlined />} 
            onClick={handleExportData}
          >
            导出
          </Button>
          
          <Button 
            icon={<FullscreenOutlined />}
            onClick={() => {
              const elem = document.documentElement;
              if (elem.requestFullscreen) {
                elem.requestFullscreen();
              }
            }}
          >
            全屏
          </Button>
        </Space>
      </div>

      <Spin spinning={loading}>
        {/* 系统概览 */}
        <Row gutter={[16, 16]} className="metrics-row">
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="CPU使用率"
                value={latestMetrics?.cpuUsage || 0}
                suffix="%"
                valueStyle={{ 
                  color: (latestMetrics?.cpuUsage || 0) > config.alertThresholds.cpu ? '#cf1322' : '#3f8600' 
                }}
                prefix={<LineChartOutlined />}
              />
              <Progress 
                percent={latestMetrics?.cpuUsage || 0} 
                showInfo={false}
                strokeColor={(latestMetrics?.cpuUsage || 0) > config.alertThresholds.cpu ? '#cf1322' : '#3f8600'}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="内存使用率"
                value={latestMetrics?.memoryUsage || 0}
                suffix="%"
                valueStyle={{ 
                  color: (latestMetrics?.memoryUsage || 0) > config.alertThresholds.memory ? '#cf1322' : '#3f8600' 
                }}
                prefix={<BarChartOutlined />}
              />
              <Progress 
                percent={latestMetrics?.memoryUsage || 0} 
                showInfo={false}
                strokeColor={(latestMetrics?.memoryUsage || 0) > config.alertThresholds.memory ? '#cf1322' : '#3f8600'}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="磁盘使用率"
                value={latestMetrics?.diskUsage || 0}
                suffix="%"
                valueStyle={{ 
                  color: (latestMetrics?.diskUsage || 0) > config.alertThresholds.disk ? '#cf1322' : '#3f8600' 
                }}
                prefix={<PieChartOutlined />}
              />
              <Progress 
                percent={latestMetrics?.diskUsage || 0} 
                showInfo={false}
                strokeColor={(latestMetrics?.diskUsage || 0) > config.alertThresholds.disk ? '#cf1322' : '#3f8600'}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="活跃连接"
                value={latestMetrics?.activeConnections || 0}
                valueStyle={{ color: '#1890ff' }}
                prefix={<DashboardOutlined />}
              />
            </Card>
          </Col>
        </Row>

        {/* 性能图表 */}
        <Row gutter={[16, 16]} className="charts-row">
          <Col xs={24} lg={12}>
            <Card title="系统性能趋势" extra={<Badge status="processing" text="实时" />}>
              <ResponsiveContainer width="100%" height={300}>
                <AreaChart data={metrics.slice(-20)}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis 
                    dataKey="timestamp" 
                    tickFormatter={(value) => new Date(value).toLocaleTimeString()}
                  />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Area 
                    type="monotone" 
                    dataKey="cpuUsage" 
                    stackId="1" 
                    stroke="#8884d8" 
                    fill="#8884d8" 
                    name="CPU使用率"
                  />
                  <Area 
                    type="monotone" 
                    dataKey="memoryUsage" 
                    stackId="1" 
                    stroke="#82ca9d" 
                    fill="#82ca9d" 
                    name="内存使用率"
                  />
                </AreaChart>
              </ResponsiveContainer>
            </Card>
          </Col>
          
          <Col xs={24} lg={12}>
            <Card title="响应时间和吞吐量" extra={<Badge status="processing" text="实时" />}>
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={metrics.slice(-20)}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis 
                    dataKey="timestamp" 
                    tickFormatter={(value) => new Date(value).toLocaleTimeString()}
                  />
                  <YAxis yAxisId="left" />
                  <YAxis yAxisId="right" orientation="right" />
                  <RechartsTooltip />
                  <Legend />
                  <Line 
                    yAxisId="left"
                    type="monotone" 
                    dataKey="responseTime" 
                    stroke="#ff7300" 
                    name="响应时间(ms)"
                    strokeWidth={2}
                  />
                  <Line 
                    yAxisId="right"
                    type="monotone" 
                    dataKey="throughput" 
                    stroke="#387908" 
                    name="吞吐量(req/s)"
                    strokeWidth={2}
                  />
                </LineChart>
              </ResponsiveContainer>
            </Card>
          </Col>
        </Row>

        {/* 告警信息 */}
        <Row gutter={[16, 16]} className="alerts-row">
          <Col xs={24} lg={16}>
            <Card 
              title="系统告警" 
              extra={
                <Space>
                  <Badge 
                    count={alertStats.total} 
                    status={alertStats.critical > 0 ? "error" : alertStats.high > 0 ? "warning" : "success"}
                  />
                  <Badge count={alertStats.critical} showZero status="error" text="严重" />
                  <Badge count={alertStats.high} showZero status="warning" text="高级" />
                  <Badge count={alertStats.medium} showZero status="processing" text="中级" />
                </Space>
              }
            >
              <Timeline>
                {alerts.slice(0, 10).map((alert) => (
                  <Timeline.Item
                    key={alert.id}
                    color={
                      alert.severity === 'critical' ? 'red' :
                      alert.severity === 'high' ? 'orange' :
                      alert.severity === 'medium' ? 'blue' : 'gray'
                    }
                    dot={
                      alert.status === 'active' ? (
                        <AlertOutlined style={{ fontSize: '16px' }} />
                      ) : (
                        <CheckCircleOutlined style={{ fontSize: '16px' }} />
                      )
                    }
                  >
                    <Space direction="vertical" style={{ width: '100%' }}>
                      <div>
                        <strong>{alert.title}</strong>
                        <Badge 
                          status={alert.status === 'active' ? 'processing' : 'success'}
                          text={alert.status === 'active' ? '活跃' : '已解决'}
                          style={{ marginLeft: 8 }}
                        />
                      </div>
                      <div>{alert.message}</div>
                      <div style={{ fontSize: '12px', color: '#999' }}>
                        {new Date(alert.timestamp).toLocaleString()}
                      </div>
                      {alert.status === 'active' && (
                        <Button 
                          size="small" 
                          type="primary"
                          onClick={() => handleAlertAcknowledge(alert.id)}
                        >
                          确认
                        </Button>
                      )}
                    </Space>
                  </Timeline.Item>
                ))}
              </Timeline>
            </Card>
          </Col>
          
          <Col xs={24} lg={8}>
            <Card title="告警统计">
              <ResponsiveContainer width="100%" height={250}>
                <PieChart>
                  <Pie
                    data={[
                      { name: '严重', value: alertStats.critical, color: '#cf1322' },
                      { name: '高级', value: alertStats.high, color: '#fa8c16' },
                      { name: '中级', value: alertStats.medium, color: '#1890ff' },
                      { name: '低级', value: alertStats.low, color: '#52c41a' }
                    ]}
                    cx="50%"
                    cy="50%"
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                    label={({ name, value }) => `${name}: ${value}`}
                  >
                    {[
                      { name: '严重', value: alertStats.critical, color: '#cf1322' },
                      { name: '高级', value: alertStats.high, color: '#fa8c16' },
                      { name: '中级', value: alertStats.medium, color: '#1890ff' },
                      { name: '低级', value: alertStats.low, color: '#52c41a' }
                    ].map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <RechartsTooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>
          </Col>
        </Row>
      </Spin>

      {/* 配置模态框 */}
      <Modal
        title="仪表板配置"
        open={configModalVisible}
        onCancel={() => setConfigModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          layout="vertical"
          initialValues={config}
          onFinish={handleConfigUpdate}
        >
          <Form.Item label="刷新间隔(毫秒)" name="refreshInterval">
            <InputNumber min={1000} max={60000} step={1000} />
          </Form.Item>
          
          <Divider>告警阈值</Divider>
          
          <Form.Item label="CPU使用率阈值(%)" name={['alertThresholds', 'cpu']}>
            <InputNumber min={0} max={100} step={5} />
          </Form.Item>
          
          <Form.Item label="内存使用率阈值(%)" name={['alertThresholds', 'memory']}>
            <InputNumber min={0} max={100} step={5} />
          </Form.Item>
          
          <Form.Item label="磁盘使用率阈值(%)" name={['alertThresholds', 'disk']}>
            <InputNumber min={0} max={100} step={5} />
          </Form.Item>
          
          <Form.Item label="响应时间阈值(ms)" name={['alertThresholds', 'responseTime']}>
            <InputNumber min={100} max={30000} step={100} />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => setConfigModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RealTimeDashboard;